package com.luo.d3s.ext.event.jdbc.handler;

import com.luo.d3s.core.domain.event.DomainEventHandler;
import com.luo.d3s.ext.event.jdbc.event.MyEventRollback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 事件回滚处理器
 *
 * @author luohq
 * @date 2023-01-24 19:53
 */
public class MyEventRollbackHandler implements DomainEventHandler<MyEventRollback> {
    private static final Logger log = LoggerFactory.getLogger(MyEventRollbackHandler.class);

    private AtomicInteger counter = new AtomicInteger(0);
    private AtomicInteger counterSuccess = new AtomicInteger(0);

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void handle(MyEventRollback domainEvent) {
        log.info("handle EventRollback types:{}, {}", domainEvent.getTypes(), domainEvent);
        //MOCK前两次失败抛异常，第三次成功
        if (3 > counter.incrementAndGet()) {
            throw new RuntimeException("回滚事件处理");
        }
        //成功计数
        counterSuccess.incrementAndGet();
    }

    public Integer getCounterSuccess() {
        return counterSuccess.get();
    }
}
